package aorise.com.frame.common;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextWatcher;
import android.text.style.AbsoluteSizeSpan;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.content.Context.CONNECTIVITY_SERVICE;

/**
 * 全局工具类
 *
 * @author liukaifu
 */
public final class Utils {
    private static final int PERMISSIONS_REQUEST_READ_PHONE_STATE = 10;

    public static Bitmap small(Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postScale(0.3f, 0.3f); // 长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizeBmp;
    }

    public static int getScreenWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }


    public static void disableSpaces(final EditText editText){
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().contains(" ")) {
                    String trim = charSequence.toString().trim();
                    editText.setText(trim);
                    editText.setSelection(i);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }


    /**
     * 沉浸式状态栏
     */
    public static void setWindowImmersiveState(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = activity.getWindow();
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

//        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
    }

    /*
     * 获取状态栏的高度
     * */
    public static int getWindowStateHeight(Context context) {
        int statusBarHeight1 = -1;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight1 = context.getResources().getDimensionPixelSize(resourceId);
        }
        return statusBarHeight1;
    }

    /**
     * edittext焦点在末尾
     **/
    public static void edittext_end(EditText ed) {
        try {
            ed.setSelection(ed.getText().toString().length());
        } catch (Exception e) {

        }
    }

    /**
     * 动态设置ListView的高度
     *
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        if (listView == null) return;
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    /**
     *      * 判断MOBILE网络是否可用
     *      * @param context
     *      * @return
     *      
     */
    public static boolean isMobileConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
            NetworkInfo mMobileNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (mMobileNetworkInfo != null) {
                return mMobileNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 直接对对象的某个属性赋值
     *
     * @param obj
     * @param property
     * @param value
     * @throws Exception
     */
    public static void setValue(Object obj, String property, Object value) throws Exception {
        Class<?> c = obj.getClass();
        Field f = c.getDeclaredField(property);
        f.set(obj, value);
    }

    /**
     * 获取一个属性对应的Get函数返回值的类型
     *
     * @param c
     * @param property
     * @return
     */
    public static Class<?> getClassByPropertyName(Class<?> c, String property) {

        try {
            char ch = (char) property.charAt(0);
            String methodName = new StringBuffer(property).delete(0, 1).insert(0, Character.toUpperCase(ch))
                    .insert(0, "get").toString();

            return c.getMethod(methodName, new Class<?>[0]).getReturnType();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过Get方法获取某个指定字段的值（String类型）
     *
     * @param obj
     * @param property
     * @return
     */
    public static String getValueStrByGetMethod(Object obj, String property) {
        try {
            Class<?> c = obj.getClass();

            char ch = (char) property.charAt(0);
            String methodName = new StringBuffer(property).delete(0, 1).insert(0, Character.toUpperCase(ch))
                    .insert(0, "get").toString();

            Method method = c.getMethod(methodName);

            Object result = method.invoke(obj);
            if (result == null) {
                return null;
            }
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 通过Object的set方法设置属性值
     *
     * @param obj
     * @param property
     * @param value
     */
    public static void setValueBySetMehtod(Object obj, String property, Object value) {
        try {
            Class<?> c = obj.getClass();

            char ch = (char) property.charAt(0);
            String methodName = new StringBuffer(property).delete(0, 1).insert(0, Character.toUpperCase(ch))
                    .insert(0, "set").toString();

            Method method = c.getMethod(methodName, getClassByPropertyName(c, property));

            method.invoke(obj, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据Get方法获取请求参数列表
     *
     * @param obj
     * @return
     */
    public static String getReqStrFromGetMethods(Object obj) {
        try {
            Class<?> c = obj.getClass();

            Method[] ms = c.getMethods();
            if (ms == null || ms.length == 0) {
                return null;
            }
            boolean isFirst = true;
            StringBuffer stringBuffer = new StringBuffer();

            for (int i = 0; i < ms.length; i++) {
                if (ms[i].getName().startsWith("get") && !ms[i].getName().equals("getClass")) {
                    String res = getValFromObj(ms[i], obj);
                    if (res != null) {
                        if (isFirst) {
                            isFirst = false;
                        } else {
                            stringBuffer.append("&");
                        }
                        stringBuffer.append(getPropertyNameFromGetMethod(ms[i].getName()));
                        stringBuffer.append("=");
                        stringBuffer.append(res);
                    }
                }
            }
            return stringBuffer.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取特定的所有Get函数返回值的描述串
     *
     * @param method
     * @param obj
     * @return
     */
    public static String getValFromObj(Method method, Object obj) {
        try {
            Object result = method.invoke(obj);

            if (result == null) {
                return null;
            }
            if (result instanceof List<?>) {
                List<?> c = (List<?>) result;
                if (c.size() == 0) {
                    return "|";
                }
                StringBuffer stringBuffer = new StringBuffer();
                // boolean isFirst = true;
                for (int i = 0; i < c.size(); i++) {
                    Object o = c.get(i);
                    if (o != null) {
                        // if (isFirst) {
                        // isFirst = false;
                        // }
                        // else {
                        // stringBuffer.append("|");
                        // }
                        stringBuffer.append(o.toString());
                        stringBuffer.append("|");
                    }
                }
                return stringBuffer.toString();
            } else {
                return result.toString();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取指定属性对应的标准Get方法
     *
     * @param id
     * @return
     */
    public static String getPropertyNameFromGetMethod(String id) {
        String str = id.substring(3, id.length());
        char ch = (char) str.charAt(0);
        return new StringBuffer(str).delete(0, 1).insert(0, Character.toLowerCase(ch)).toString();
    }

    // public static void writeByteArrayToFile(byte[] bytes, File file)
    // {
    // if (!file.exists()){
    // file.createNewFile();
    // }
    // FileOutputStream fileOutputStream = new FileOutputStream(file);
    // fileOutputStream.write(bytes);
    // }

    /**
     * 从一个文件中读取内容，转化成byte[],注意必须是小文件
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static byte[] readByteArrayFromFile(File file) throws Exception {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        int length = -1;
        while ((length = fileInputStream.read(buffer)) > 0) {
            byteArrayOutputStream.write(buffer, 0, length);
        }
        byteArrayOutputStream.flush();
        fileInputStream.close();

        byte[] result = byteArrayOutputStream.toByteArray();

        byteArrayOutputStream.close();

        return result;
    }

    /**
     * 从一个输入流读出byte[],以输入流有EOF标志为准
     *
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static byte[] readByteArrayFromStream(InputStream inputStream) throws Exception {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length = -1;
        while ((length = inputStream.read(buffer)) > 0) {
            byteArrayOutputStream.write(buffer, 0, length);
        }
        byteArrayOutputStream.flush();
        inputStream.close();

        byte[] result = byteArrayOutputStream.toByteArray();

        byteArrayOutputStream.close();

        return result;
    }

    // /**

    /**
     * 判断一个字符串是不是空串
     *
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        return str == null || str.equals("");
    }
    // * 隐藏手机号中间部分
    // *
    // * @param str
    // * @return
    // */
    // public static String ChangeMobileNum(String str) {
    // String mobileNum = null;
    // if (Global.MOBILE_NUM_LENGTH.equals(str.length())) {
    // String num = str.substring(0, 3);
    // String num1 = str.substring(7, 11);
    // mobileNum = num + "****" + num1;
    // }
    // return mobileNum;
    // }

    /**
     * 得到自定义的progressDialog
     *
     * @param context
     * @param msg
     * @return
     */
    // public static Dialog createLoadingDialog(Context context, String msg) {
    //
    // LayoutInflater inflater = LayoutInflater.from(context);
    // View v = inflater.inflate(R.layout.wobaifu_loading_dialog, null);//
    // 得到加载view
    // LinearLayout layout = (LinearLayout) v.findViewById(R.id.dialog_view);//
    // 加载布局
    // // main.xml中的ImageView
    // ImageView spaceshipImage = (ImageView) v.findViewById(R.id.img);
    // // TextView tipTextView = (TextView) v.findViewById(R.id.tipTextView);//
    // // 提示文字
    // // 加载动画
    // Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(
    // context, R.anim.loading_animation);
    // // 使用ImageView显示动画
    // spaceshipImage.startAnimation(hyperspaceJumpAnimation);
    // // tipTextView.setText(msg);// 设置加载信息
    //
    // Dialog loadingDialog = new Dialog(context, R.style.loading_dialog);//
    // 创建自定义样式dialog
    //
    // loadingDialog.setCancelable(false);// 不可以用“返回键”取消
    // loadingDialog.setCancelable(true);// 设置进度条是否可以按退回键取消
    // loadingDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕外部不取消
    //
    // loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(
    // LinearLayout.LayoutParams.FILL_PARENT,
    // LinearLayout.LayoutParams.FILL_PARENT));// 设置布局
    // return loadingDialog;
    //
    // }

    /**
     * 手机号码号段
     */
    public static final String[] MOBILE_HEADER = new String[]{"133", "153", "180", "181", "189", "130", "131", "132",
            "145", "155", "156", "185", "186", "134", "135", "136", "137", "138", "139", "147", "150", "151", "152",
            "157", "158", "159", "182", "183", "184", "187", "188", "170"};

    /**
     * 校验手机号码是否正确
     *
     * @param mbl
     * @return
     */
    public static boolean checkMblNo(String mbl) {
        if (Utils.isEmpty(mbl)) {
            return false;
        }

        Pattern pattern = Pattern.compile("^1[0-9]{10}$");
        Matcher matcher = pattern.matcher(mbl);

        if (!matcher.find()) {
            return false;
        }

        for (int i = 0; i < MOBILE_HEADER.length; i++) {
            String head = MOBILE_HEADER[i];
            if (mbl.startsWith(head)) {
                return true;
            }

        }

        return false;
    }

    /**
     * Toast
     *
     * @param context
     * @param contentOfToast
     */
    public static void showToast(Context context, String contentOfToast) {
        Toast t3 = Toast.makeText(context, contentOfToast, Toast.LENGTH_LONG);
        t3.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 0);
        t3.setMargin(0f, 0.5f);
        t3.show();
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        try {
            final float scale = context.getResources().getDisplayMetrics().density;
            return (int) (dpValue * scale + 0.5f);
        } catch (Exception e) {
            // TODO: handle exception
            return 0;
        }

    }

    /**
     * 获取titlebar高度
     **/
    public static int getStatusBarHeight(Fragment fragment) {
        int result = 0;
        int resourceId = fragment.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = fragment.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 获取titlebar高度
     **/
    public static int getStatusBarHeight(Activity fragment) {
        try {
            int result = 0;
            int resourceId = fragment.getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                result = fragment.getResources().getDimensionPixelSize(resourceId);
            }
            return result;
        } catch (Exception e) {
            // TODO: handle exception
            return 0;
        }

    }

    /**
     * 获取titlebar高度
     **/
    public static int getStatusBarHeights(Context fragment) {
        int result = 0;
        int resourceId = fragment.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = fragment.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static String getVersion(Context context)// 获取版本号
    {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return "null";
        }
    }

    /*** 清空空格以及回车等 ****/
    public static String getTrueString(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }

        if (dest.startsWith("\ufeff")) {
            return str.substring(1);
        } else {
            return dest;
        }

    }

    /**
     * 根据屏幕分辨率返回正确的大小
     **/
    public static float GETTRUESIZE(float textsize, Activity activity) {
        return dip2px(activity, textsize);
    }

    /*** 时间戳转换成时间 @return yyyy-MM-dd HH:mm:ss ***/
    public static String TimeStamp4Date(String timestampString) {
        try {
            Long timestamp = Long.parseLong(timestampString) * 1000;
            // :ss
            String date = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(timestamp));
            return date;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "未知";
    }

    /*** 时间戳转换成时间 @return yyyy-MM-dd ***/
    public static String TimeStampDate(String timestampString) {
        try {

            Long timestamp = Long.parseLong(timestampString) * 1000;
            // :ss
            String date = new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date(timestamp));
            return date;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "未知";
    }

    /**
     * HH:mm:ss
     *
     * @param date
     * @return
     */
    private static String TAG = "Utils";


    public static String getHMS2(long value) {
//		Calendar calendar= Calendar.getInstance();
//		calendar.setTimeInMillis(timetemp);
//		SimpleDateFormat fmat=new SimpleDateFormat("HH:mm:ss");
//		String time=fmat.format(calendar.getTime());
        value = value / 1000;
        String hours = String.valueOf(value / 3600);
        if (hours.length() == 1) {
            hours = "0" + hours;
        }
        String minites = String.valueOf(value % 3600 / 60);
        if (minites.length() == 1) {
            minites = "0" + minites;
        }
        String seconds = String.valueOf(value % 3600 % 60);
        if (seconds.length() <= 1) {
            seconds = "0" + seconds;
        }

        return hours + ":" + minites + ":" + seconds;
    }

    /*
* 将时间戳转换为时间 时分秒
*/
    public static String stampToDate(String s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    /*** 时间戳转换成时间 @return MM-dd ***/
    public static String TimeStamp4MomData(String timestampString) {
        try {
            Long timestamp = Long.parseLong(timestampString) * 1000;

            String date = new java.text.SimpleDateFormat("MM-dd").format(new java.util.Date(timestamp));
            return date;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "未知";
    }

    public static float dp2px(Resources resources, float dp) {
        final float scale = resources.getDisplayMetrics().density;
        return dp * scale + 0.5f;
    }

    /**
     * 打印错误信息
     **/
    public static String errInfo(Exception e) {
        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            // 将出错的栈信息输出到printWriter中
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
            }
        }
        return sw.toString();
    }

    public static float dp2pxs(float dp) {
        final float scale = Resources.getSystem().getDisplayMetrics().density * dp;
        return scale;
    }

    public static float sp2px(Resources resources, float sp) {
        final float scale = resources.getDisplayMetrics().scaledDensity;
        return sp * scale;
    }

    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 从SD卡获取头像
     */
    public static Bitmap getBitmapFromSD() {
        // String path = "/storage/emulated/0/path/.storage.jpg";
        String path = android.os.Environment.getExternalStorageDirectory().getAbsolutePath() + "/path/.storage.jpg";
        File mFile = new File(path); // 若该文件存在
        if (mFile.exists()) {
            Bitmap bitmap = BitmapFactory.decodeFile(path);
            return bitmap;
        }
        return null;
    }

    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
        if (bitmap == null) {
            return null;
        }

        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }






    /**
     * 弹出dialog
     **/

    /**
     * 控制键盘的dialog
     **/

    // 获取屏幕高度
    public static int getScreenHeight(Activity activity) {
        DisplayMetrics metric = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;
        int height = metric.heightPixels;
        return height;
    }

    // 获取屏幕宽度
    public static int getScreenWidth(Activity activity) {
        DisplayMetrics metric = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;
        int height = metric.heightPixels;
        return width;
    }

    public static int getAndroiodScreenProperty(Activity activity) {
        WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;         // 屏幕宽度（像素）
        int height = dm.heightPixels;       // 屏幕高度（像素）
        float density = dm.density;         // 屏幕密度（0.75 / 1.0 / 1.5）
        int densityDpi = dm.densityDpi;     // 屏幕密度dpi（120 / 160 / 240）
        // 屏幕宽度算法:屏幕宽度（像素）/屏幕密度
        int screenWidth = (int) (width / density);  // 屏幕宽度(dp)
        int screenHeight = (int) (height / density);// 屏幕高度(dp)

        return screenWidth;
    }


    //安卓中像素px和dp的转换：
    public static int Dp2Px(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density; //当前屏幕密度因子
        return (int) (dp * scale + 0.5f);
    }

    public static int Px2Dp(Context context, float px) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

    /**
     * 把一个List转成,号分割的字符串
     **/
    public static String listToString(List<String> stringList) {
        if (stringList == null) {
            return null;
        }
        StringBuffer result = new StringBuffer();
        boolean flag = false;
        for (String str : stringList) {
            if (flag) {
                result.append(",");
            } else {
                flag = true;
            }
            result.append(str);
        }
        return result.toString();
    }

    public static String getNativePhoneNumber(Activity context) {
        int permissionCheck = ContextCompat.checkSelfPermission(context,
                Manifest.permission.READ_PHONE_STATE);
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(context,
                    new String[]{Manifest.permission.READ_PHONE_STATE},
                    PERMISSIONS_REQUEST_READ_PHONE_STATE);
        } else {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String NativePhoneNumber = null;
            NativePhoneNumber = telephonyManager.getLine1Number();
            if (null != NativePhoneNumber && !NativePhoneNumber.equals("")) {
                return NativePhoneNumber;
            }
        }
        return "";
    }

    public static String getMac() {
        String macSerial = "";
        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);

            String line;
            while ((line = input.readLine()) != null) {
                macSerial += line.trim();
            }

            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return macSerial;
    }

    public static boolean checkEnable(Context paramContext) {
        boolean i = false;
        NetworkInfo localNetworkInfo = ((ConnectivityManager) paramContext.getSystemService(CONNECTIVITY_SERVICE))
                .getActiveNetworkInfo();
        if ((localNetworkInfo != null) && (localNetworkInfo.isAvailable()))
            return true;
        return false;
    }

    /**
     * 将ip的整数形式转换成ip形式 * * @param ipInt * @return
     */
    public static String int2ip(int ipInt) {
        StringBuilder sb = new StringBuilder();
        sb.append(ipInt & 0xFF).append(".");
        sb.append((ipInt >> 8) & 0xFF).append(".");
        sb.append((ipInt >> 16) & 0xFF).append(".");
        sb.append((ipInt >> 24) & 0xFF);
        return sb.toString();
    }

    /**
     * 获取当前ip地址 * * @param context * @return
     */
    public static String getLocalIpAddress(Context context) {
        try {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int i = wifiInfo.getIpAddress();
            return int2ip(i);
        } catch (Exception ex) {
            return " 获取IP出错鸟!!!!请保证是WIFI,或者请重新打开网络!\n" + ex.getMessage();
        }
    }


    /**
     * 设置文字的hint文字颜色
     **/
    public static void setHintText(TextView edit, String hintText, int color) {
        SpannableString ss = new SpannableString(hintText);
        // 新建一个属性对象,设置文字的大小
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(10, true);
        // 附加属性到文本
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 设置hint
        edit.setText(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
        edit.setTextColor(color);
    }


    @SuppressLint("NewApi")
    public static boolean isNavigationBarShow(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            Display display = activity.getWindowManager().getDefaultDisplay();
            Point size = new Point();
            Point realSize = new Point();
            display.getSize(size);
            display.getRealSize(realSize);
            return realSize.y != size.y;
        } else {
            boolean menu = ViewConfiguration.get(activity).hasPermanentMenuKey();
            boolean back = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
            if (menu || back) {
                return false;
            } else {
                return true;
            }
        }
    }

    public static int getNavigationBarHeight(Activity activity) {
        int navigationBarHeight = 0;
        Resources rs = activity.getResources();
        int id = rs.getIdentifier("navigation_bar_height", "dimen", "android");
        if (id > 0 && isNavigationBarShow(activity)) {
            navigationBarHeight = rs.getDimensionPixelSize(id);
        }
        return navigationBarHeight;
    }

    /**
     * 利用java原生的摘要实现SHA256加密
     *
     * @param str 加密后的报文
     * @return
     */
    public static String getSHA256StrJava(String str) {
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodeStr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodeStr;
    }

    /**
     * 将byte转为16进制
     *
     * @param bytes
     * @return
     */
    private static String byte2Hex(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }



    /**
     * 设置edittext只能输入小数点后两位
     *
     * @param editText
     */
    public static void afterDowTwo(final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
                if (s.toString().contains(".")) {
                    if (s.toString().indexOf(".") > 9) {
                        s = s.toString().subSequence(0, 9) + s.toString().substring(s.toString().indexOf("."));
                        editText.setText(s);
                        editText.setSelection(9);
                    }
                } else {
                    if (s.toString().length() > 9) {
                        s = s.toString().subSequence(0, 9);
                        editText.setText(s);
                        editText.setSelection(9);
                    }
                }
                // 判断小数点后只能输入两位
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                }
                //如果第一个数字为0，第二个不为点，就不允许输入
                if (s.toString().startsWith("0") && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                // 限制最多能输入9位整数

            }
        });
    }
} 
